<template>
  <div class="sms-code" :class="inline?'sms-code-inline':''">
    <e-cellbox :gutter="10">
      <e-cell-item>
        <el-input v-bind="$props" v-on="$listeners" :action="null" :params="null">
          <template v-if="codeIcon" slot="prepend"><i class="iconfont" v-html="codeIcon"></i></template>
        </el-input>
      </e-cell-item>
      <e-cell-item>
        <component
          :is="device=='mobile'?'button':'el-button'"
          :loading="loading"
          :disabled="btnDisabled || counter > 0"
          :type="device=='mobile'?'button':undefined"
          @click="handle"
          >
          {{counter > 0 ? `重新发送(${counter})` : '获取验证码'}}
        </component>
      </e-cell-item>
    </e-cellbox>
    <div v-if="isSend" class="sms-code-help small weak">验证码已发送，15分钟内输入有效。</div>
  </div>
</template>

<script>
  import { Input } from '@element-ui'
  import {Cellbox, CellItem} from './cellbox'
  export default {
    componentName: 'ESmsCode',
    components: {
      ElInput: Input,
      ECellbox: Cellbox,
      ECellItem: CellItem
    },
    props: {
      ...Input.props,
      placeholder: {
        type: String,
        default: '请输入验证码'
      },
      maxlength: {
        type: Number,
        default: 6
      },
      btnDisabled: {
        type: Boolean,
        default: false
      },
      inline: {
        type: Boolean,
        default: false
      },
      duration: {
        type: Number,
        default: 60000
      },
      action: {
        default: '/guest/sendValidateCode'
      },
      params: {
        default: {}
      },
      codeIcon: {
        type: String,
        default: '&#xe600;'
      },
      device: {
        type: String
      }
    },
    data () {
      return {
        loading: false,
        isSend: false,
        counter: 0
      }
    },
    methods: {
      handle () {
        require.ensure([], (r) => {
          let fetch = require('fetch').default
          let options = {
            url: this.action,
            params: Object.assign({randomKey: '', validateCode: ''}, this.params),
            options: {context: this}
          }
          fetch(options).then((res) => {
            this.isSend = true
            this.counter = this.duration / 1000
            this.$interval = setInterval(() => {
              this.counter = this.counter - 1
            }, 1000)
          })
        })
      }
    }
  }
</script>
